
using System;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SP2010InPlaceRecordsViewer.Features.InPlaceRecordsViewer
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("dce63e7f-4695-47ba-97a4-6c3a474cd20b")]
    public class InPlaceRecordsViewerEventReceiver : SPFeatureReceiver
    {
        #region Constants

        private const string JOB_NAME = "In Place Records Viewer Timer Job";
        private const string JOB_NAME_DESCRIPTION = "Daily Timer Job that re-creates and re-populates the administrator visible InPlaceRecords list where the InPlaceRecordsViewer feature is activated";

        private const int JOB_NAME_BEGIN_HOUR = 1;
        private const int JOB_NAME_END_HOUR = 3;
        private const int JOB_NAME_BEGIN_MINUTE = 1;
        private const int JOB_NAME_END_MINUTE = 59;
        private const int JOB_NAME_BEGIN_SECOND = 1;
        private const int JOB_NAME_END_SECOND = 59;

        private const string ONE_TIME_JOB_NAME = "In Place Records Viewer Timer Job - One Time";
        private const string ONE_TIME_JOB_NAME_DESCRIPTION = "One time Timer Job that creates and populates the administrator visible InPlaceRecords list once the InPlaceRecordsViewer feature is activated";
        
        private const int ONE_TIME_JOB_WAIT_MINUTES = 3;

        private const string RECORDS_LIST_TITLE = "In Place Records";

        #endregion

        #region Overrides

        #region FeatureActivated
        /// <summary>
        /// Upon activation of this feature, links to the service applications and the other links
        /// </summary>
        /// <param name="properties"></param>
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    var site = properties.Feature.Parent as SPSite;

                    if (site != null)
                    {
                        foreach (var job in site.WebApplication.JobDefinitions.Where(job => job.Name == JOB_NAME))
                        {
                            job.Delete();
                        }

                        var timerJob = new InPlaceRecordsViewerTimerJob(JOB_NAME, site.WebApplication);
                        timerJob.CustomDescription = JOB_NAME_DESCRIPTION;

                        var schedule = new SPDailySchedule();

                        schedule.BeginHour = JOB_NAME_BEGIN_HOUR;
                        schedule.EndHour = JOB_NAME_END_HOUR;
                        schedule.BeginMinute = JOB_NAME_BEGIN_MINUTE;
                        schedule.EndMinute = JOB_NAME_END_MINUTE;
                        schedule.BeginSecond = JOB_NAME_BEGIN_SECOND;
                        schedule.EndSecond = JOB_NAME_END_SECOND;

                        timerJob.Schedule = schedule;
                        timerJob.Update();

                        try
                        {
                            foreach (var job in site.WebApplication.JobDefinitions.Where(job => job.Name == ONE_TIME_JOB_NAME))
                            {
                                job.Delete();
                            }

                            var oneTimeTimerJob = new InPlaceRecordsViewerTimerJob(ONE_TIME_JOB_NAME, site.WebApplication);
                            oneTimeTimerJob.CustomDescription = ONE_TIME_JOB_NAME_DESCRIPTION;

                            var oneTimeSchedule = new SPOneTimeSchedule(DateTime.Now.AddMinutes(ONE_TIME_JOB_WAIT_MINUTES));
                            oneTimeTimerJob.Schedule = oneTimeSchedule;
                            oneTimeTimerJob.Update();
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Unable to execute " + JOB_NAME, ex);
                        }
                    
                    }
                }
                catch (Exception ex)
                {
                    SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("InPlaceRecordsViewerEventReceiver", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
                    throw;
                }
            });
        }


        #endregion

        #region FeatureDeactivating
        /// <summary>
        /// Upon deactivation of this feature, links to the service applications and the other links
        /// configured in the feature properties will be removed from the Central Administration 
        /// resources list that is shown on the Central Administration Homepage
        /// </summary>
        /// <param name="properties"></param>
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    var site = properties.Feature.Parent as SPSite;

                    if (site != null)
                    {
                        foreach (var job in site.WebApplication.JobDefinitions.Where(job => job.Name == JOB_NAME))
                        {
                            job.Delete();
                        }

                        foreach (var job in site.WebApplication.JobDefinitions.Where(job => job.Name == ONE_TIME_JOB_NAME))
                        {
                            job.Delete();
                        }

                        using (var rootWeb = site.OpenWeb())
                        {
                            var recordsViewerList = rootWeb.Lists.TryGetList(RECORDS_LIST_TITLE);

                            recordsViewerList.Delete();
                            rootWeb.Update();
                        }
                    }
                }
                catch (Exception ex)
                {
                    SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("InPlaceRecordsViewerEventReceiver", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
                    throw;
                }
            });
        }
        #endregion

        #endregion

        #region Private Methods



        #endregion
    }
}
